<!-- 从front-page项目合并的首页 -->
<template>
  <div class="dashboard-container">
    <div class="main-content">
      <div class="header">
        <h1>智慧茶园生态看板</h1>
        <!-- 添加待办邮箱图标 -->
        <div class="todo-inbox" @click="todoDialogVisible = true">
          <svg-icon icon-class="email" class-name="icon-mail" />
          <span v-if="unreadTodoCount > 0" class="badge">{{ unreadTodoCount }}</span>
        </div>
      </div>
      
      <div class="stat-cards">
        <div class="custom-stat-card blue-card">
          <div class="icon-box">
            <svg-icon icon-class="tearoom" class-name="icon-svg" />
          </div>
          <div class="content">
            <div class="title">茶园面积</div>
            <div class="value">120亩</div>
          </div>
        </div>
        
        <div class="custom-stat-card green-card">
          <div class="icon-box">
            <svg-icon icon-class="tea" class-name="icon-svg" />
          </div>
          <div class="content">
            <div class="title">茶叶产量</div>
            <div class="value-container">
              <div class="value">{{ teaProduction }}kg</div>
              <div class="change" :class="{ 'up': teaProductionTrend === 'up', 'down': teaProductionTrend === 'down' }">{{ teaProductionChange }}</div>
            </div>
          </div>
        </div>
        
        <div class="custom-stat-card yellow-card">
          <div class="icon-box">
            <svg-icon icon-class="bug" class-name="icon-svg" />
          </div>
          <div class="content">
            <div class="title">虫情预警</div>
            <div class="value-container">
              <div class="value" :class="{'warning-low': pestWarningLevel === '低', 'warning-medium': pestWarningLevel === '中', 'warning-high': pestWarningLevel === '高'}">{{ pestWarningLevel }}</div>
            </div>
          </div>
        </div>
        
        <!-- 设备状况卡片 -->
        <div class="custom-stat-card" :class="{'green-card': deviceStatus === '正常', 'red-card': deviceStatus === '异常'}">
          <div class="icon-box">
            <svg-icon icon-class="monitor" class-name="icon-svg" />
          </div>
          <div class="content">
            <div class="title">设备状况</div>
            <div class="value" :class="{'device-normal': deviceStatus === '正常', 'device-error': deviceStatus === '异常'}">{{ deviceStatus }}</div>
          </div>
        </div>
      </div>
      
      <div class="charts-container">
        <div class="chart-section">
          <div class="chart-item">
            <div class="chart-title">
              <svg-icon icon-class="chart" class-name="icon-svg" />
              <span>茶旅管理分布</span>
            </div>
            <Chart ref="pieChartRef" chartType="pie" title="" />
          </div>
          
          <div class="chart-item">
            <div class="chart-title">
              <svg-icon icon-class="weather" class-name="icon-svg" />
              <span>气象情况</span>
            </div>
            <Chart ref="weatherChartRef" chartType="bar" title="" />
          </div>
        </div>
        
        <!-- 虫情防治日历和措施区域 -->
        <div class="pest-calendar-section">
          <div class="section-title">
            <svg-icon icon-class="date" class-name="icon-svg" />
            <span>虫情防治措施</span>
          </div>
          <div class="pest-calendar-container">
            <!-- 环境健康指数区域 -->
            <div class="calendar-wrapper">
              <PestHistory ref="pestHistoryRef" />
            </div>
            
            <!-- 虫情防治措施和日历区域 -->
            <div class="measures-wrapper">
              <div class="measures-content">
                <PestMeasures ref="pestMeasuresRef" />
                <PestCalendar @daySelected="handleDateSelect" class="calendar-component" />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 设备异常弹窗 -->
      <el-dialog
        title="设备异常警告"
        v-model="deviceErrorDialogVisible"
        width="480px"
        :show-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        class="device-error-dialog-container"
        :modal-class="'device-error-modal'"
        :z-index="9999"
        append-to-body
      >
        <div class="device-error-dialog">
          <div class="error-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="error-alert">警报警报！</div>
          <div class="error-title">检测到茶园设备异常情况</div>
          <div class="error-content">
            <p><strong>异常设备：</strong>3号灌溉控制器</p>
            <p><strong>异常类型：</strong>通信中断</p>
            <p><strong>异常时间：</strong>2024年3月30日 08:23:45</p>
            <p><strong>影响范围：</strong>东区茶园约30亩</p>
            <p><strong>潜在风险：</strong>可能导致灌溉中断，影响茶树生长，若持续超过24小时可能影响产量</p>
          </div>
          <div class="error-solution">
            <p><strong>建议处理方案：</strong></p>
            <ol>
              <li>检查设备电源和网络连接状态</li>
              <li>重置设备通信模块</li>
              <li>联系技术支持人员进行远程诊断</li>
              <li>若无法恢复，请更换备用设备确保灌溉正常进行</li>
            </ol>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="warning" @click="handleLaterProcess">稍后处理</el-button>
            <el-button type="primary" @click="handleDeviceError">立即处理</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 待办事项弹窗 -->
      <el-dialog
        title="待办事项"
        v-model="todoDialogVisible"
        width="500px"
        :show-close="true"
        class="todo-dialog-container"
      >
        <div class="todo-dialog">
          <div v-if="todoItems.length === 0" class="empty-todo">
            <i class="el-icon-document"></i>
            <p>暂无待办事项</p>
          </div>
          <div v-else class="todo-list">
            <div v-for="(item, index) in todoItems" :key="index" class="todo-item">
              <div class="todo-item-header">
                <span class="todo-title">{{ item.title }}</span>
                <span class="todo-time">{{ item.time }}</span>
              </div>
              <div class="todo-content">
                <p>{{ item.content }}</p>
              </div>
              <div class="todo-footer">
                <span class="todo-type" :class="'todo-type-' + item.type">{{ item.typeText }}</span>
                <el-button size="small" @click="markAsRead(index)">标记已读</el-button>
              </div>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showHistoryTodos">历史记录</el-button>
            <el-button type="primary" @click="markAllAsRead" :disabled="todoItems.length === 0">一键已读</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 历史记录弹窗 -->
      <el-dialog
        title="历史记录"
        v-model="historyDialogVisible"
        width="500px"
        :show-close="true"
        class="history-dialog-container"
      >
        <div class="history-dialog">
          <div v-if="historyItems.length === 0" class="empty-history">
            <i class="el-icon-document"></i>
            <p>暂无历史记录</p>
          </div>
          <div v-else class="history-list">
            <div v-for="(item, index) in historyItems" :key="index" class="history-item">
              <div class="history-item-header">
                <span class="history-title">{{ item.title }}</span>
                <span class="history-time">{{ item.time }}</span>
              </div>
              <div class="history-content">
                <p>{{ item.content }}</p>
              </div>
              <div class="history-footer">
                <span class="history-type" :class="'history-type-' + item.type">{{ item.typeText }}</span>
                <span class="history-status">已处理</span>
              </div>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="historyDialogVisible = false">关闭</el-button>
            <el-button type="danger" @click="clearHistory" :disabled="historyItems.length === 0">清空历史</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import StatCard from '@/components/Homepage/StatCard.vue'
import Chart from '@/components/Homepage/Chart.vue'
import PestCalendar from '@/components/Homepage/PestCalendar.vue'
import PestMeasures from '@/components/Homepage/PestMeasures.vue'
import PestHistory from '@/components/Homepage/PestHistory.vue'
import EnvHealthIndex from '@/components/Homepage/EnvHealthIndex.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'

// 用于存储日历选中的日期
const selectedDate = ref(null);
// 组件引用
const pestHistoryRef = ref(null);
const pestMeasuresRef = ref(null);
const envHealthIndexRef = ref(null);
const chartRef = ref(null);
const weatherChartRef = ref(null);
const pieChartRef = ref(null);

// 茶叶产量数据
const teaProduction = ref(85);
const teaProductionChange = ref('+12');
const teaProductionTrend = ref('up'); // 'up' 或 'down'

// 虫情预警级别数据
const pestWarningLevel = ref('低');
const pestWarningPhase = ref('预防期'); // 预防期、高发期、关键期

// 存储前一天的产量数据
const previousDayProduction = ref(85);
const previousDate = ref(null);

// 设备状态数据
const deviceStatus = ref('正常');
const deviceErrorDialogVisible = ref(false);

// 新增待办事项相关状态
const todoDialogVisible = ref(false);
const historyDialogVisible = ref(false);
const unreadTodoCount = ref(0);
const todoItems = ref([]);
const historyItems = ref([]);

// 根据生态评分生成茶叶产量（85-150kg之间）
function generateTeaProduction(ecoScore) {
  // 生态评分范围通常在60-95之间
  // 将这个范围映射到茶叶产量范围85-150
  
  // 设定最低和最高生态评分边界
  const minEcoScore = 60;
  const maxEcoScore = 95;
  
  // 设定对应的茶叶产量范围
  const minProduction = 85;
  const maxProduction = 150;
  
  // 确保生态评分在有效范围内
  const validEcoScore = Math.max(minEcoScore, Math.min(maxEcoScore, ecoScore));
  
  // 计算评分在总范围中的比例
  const ratio = (validEcoScore - minEcoScore) / (maxEcoScore - minEcoScore);
  
  // 根据比例计算对应的茶叶产量
  const production = minProduction + Math.round(ratio * (maxProduction - minProduction));
  
  return production;
}

// 计算与前一天的产量差值
function calculateProductionChange(currentEcoScore, previousProduction) {
  // 使用当前生态评分计算当前产量
  const currentProduction = generateTeaProduction(currentEcoScore);
  
  // 使用前一天的产量作为比较基准
  // 如果没有提供前一天的产量，使用存储的previousDayProduction
  const prevProduction = previousProduction !== null ? previousProduction : previousDayProduction.value;
  
  // 计算差值
  const difference = currentProduction - prevProduction;
  
  return {
    production: currentProduction,
    difference: difference,
    trend: difference >= 0 ? 'up' : 'down',
    changeText: difference >= 0 ? `+${difference}kg` : `${difference}kg`
  };
}

// 根据日期判断虫情预警级别和阶段
function determinePestWarningLevel(date) {
  // 确保date是Date对象
  const dateObj = date instanceof Date ? date : new Date(date);
  
  // 检查在PestMeasures组件中是否有对应的防治措施
  if (pestMeasuresRef.value) {
    const hasMeasures = pestMeasuresRef.value.checkHasMeasures(dateObj);
    
    // 如果没有措施，则设置为"低"级别，阶段设为空
    if (!hasMeasures) {
      pestWarningLevel.value = '低';
      pestWarningPhase.value = '';
      return;
    }
  }
  
  // 以下是有防治措施的情况，继续原来的逻辑
  // 获取日期信息
  const year = dateObj.getFullYear();
  const month = dateObj.getMonth();
  const day = dateObj.getDate();
  
  // 检查是否是2025年的固定日期事件
  const fixedDays = month === 3 ? [1, 5] : [1, 3, 5]; // 4月只有1日和5日有固定事件
  
  if (fixedDays.includes(day)) {
    if (day === 3) {
      // 蓝点-高发期
      pestWarningLevel.value = '中';
      pestWarningPhase.value = '高发期';
    } else if (day === 5) {
      // 绿点-预防期
      pestWarningLevel.value = '低';
      pestWarningPhase.value = '预防期';
    } else if (day === 1) {
      // 绿点-预防期
      pestWarningLevel.value = '低';
      pestWarningPhase.value = '预防期';
    }
    return;
  }
  
  // 检查是否在月度事件列表中
  const monthlyDays = {
    0: [7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31], // 1月
    1: [2, 4, 8, 10, 12, 14, 18, 20, 22, 24, 26, 28], // 2月
    2: [7, 8, 10, 11, 13, 14, 16, 18, 19, 21, 22, 24, 25, 27, 28, 30, 31], // 3月
    3: [2, 4, 6, 9, 12, 15, 16, 18, 20, 22, 24, 26, 28, 30], // 4月
    4: [1, 3, 5, 8, 10, 12, 14, 17, 20, 22, 23, 25, 27, 29, 31], // 5月
    5: [2, 4, 7, 9, 11, 13, 16, 18, 20, 22, 25, 27, 29], // 6月
    6: [1, 3, 5, 7, 10, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31], // 7月
    7: [2, 4, 6, 8, 11, 14, 16, 18, 20, 22, 24, 26, 28, 30], // 8月
    8: [2, 4, 6, 8, 10, 12, 14, 17, 19, 21, 23, 25, 27, 29], // 9月
    9: [1, 3, 5, 7, 9, 11, 13, 15, 18, 21, 23, 25, 27, 29, 31], // 10月
    10: [2, 4, 6, 8, 10, 12, 15, 18, 20, 22, 24, 26, 28, 30], // 11月
    11: [2, 4, 6, 9, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] // 12月
  };
  
  if (monthlyDays[month] && monthlyDays[month].includes(day)) {
    // 根据规律确定类型
    if (day === 19) {
      // 特殊日期 - 高发期
      pestWarningLevel.value = '中';
      pestWarningPhase.value = '高发期';
    } else {
      // 按照规律分配类型
      const types = ['prevention', 'outbreak', 'critical'];
      const index = Math.floor((month * 31 + day) % 3);
      const type = types[index];
      
      if (type === 'prevention') {
        // 绿点 - 预防期
        pestWarningLevel.value = '低';
        pestWarningPhase.value = '预防期';
      } else if (type === 'outbreak') {
        // 蓝点 - 高发期
        pestWarningLevel.value = '中';
        pestWarningPhase.value = '高发期';
      } else if (type === 'critical') {
        // 橙点 - 关键期
        pestWarningLevel.value = '高';
        pestWarningPhase.value = '关键期';
      }
    }
    return;
  }
  
  // 默认为低级别
  pestWarningLevel.value = '低';
  pestWarningPhase.value = '';
}

// 日历日期选中事件处理
function handleDateSelect(day) {
  // 确保date是日期对象
  const dateObj = day.date instanceof Date ? day.date : new Date(day.date);
  
  // 检查是否是3月30日，设置设备状态
  const month = dateObj.getMonth();
  const date = dateObj.getDate();
  if (month === 2 && date === 30) { // JavaScript中月份从0开始，2代表3月
    deviceStatus.value = '异常';
    // 如果是第一次点击3月30日，则显示弹窗
    if (!deviceErrorDialogVisible.value) {
      setTimeout(() => {
        deviceErrorDialogVisible.value = true;
      }, 300);
    }
  } else {
    deviceStatus.value = '正常';
  }
  
  // 获取前一天的日期（日历上的前一天）
  const previousDateObj = new Date(dateObj);
  previousDateObj.setDate(previousDateObj.getDate() - 1);
  
  // 先保存当前选择的日期
  selectedDate.value = day;
  
  // 检查是否有防治措施
  let hasMeasures = false;
  if (pestMeasuresRef.value) {
    hasMeasures = pestMeasuresRef.value.checkHasMeasures(dateObj);
  }
  
  // 检查前一天是否有防治措施
  let previousDayHasMeasures = false;
  if (pestMeasuresRef.value) {
    previousDayHasMeasures = pestMeasuresRef.value.checkHasMeasures(previousDateObj);
  }
  
  // 更新虫情预警级别
  determinePestWarningLevel(dateObj);
  
  // 直接更新当前选中日期的环境健康指数
  if (pestHistoryRef.value) {
    // 首先更新当前日期的环境健康指数数据
    pestHistoryRef.value.updateData(dateObj);
    
    // 获取前一天的生态评分，但不更新界面显示
    let previousEcoScore = 80; // 默认生态评分
    let prevProduction = 100; // 默认茶叶产量
    
    // 计算前一天的生产数据
    const getAndStoreYesterdayData = () => {
      // 如果可以计算前一天的平均分，就不在界面上显示，只获取数值
      if (pestHistoryRef.value.calculateAverageScore) {
        previousEcoScore = pestHistoryRef.value.calculateAverageScore();
        
        // 根据前一天的生态评分和防治措施，计算前一天应有的产量
        if (!previousDayHasMeasures) {
          const improvedEcoScore = Math.min(95, previousEcoScore + 8);
          prevProduction = generateTeaProduction(improvedEcoScore);
        } else {
          // 获取前一天的虫情预警级别
          let prevPestWarningLevel = '低'; // 默认值
          const prevFixedDays = previousDateObj.getMonth() === 3 ? [1, 5] : [1, 3, 5];
          
          if (prevFixedDays.includes(previousDateObj.getDate())) {
            if (previousDateObj.getDate() === 3) {
              prevPestWarningLevel = '中';
            }
          } else {
            // 根据规律确定类型
            const types = ['prevention', 'outbreak', 'critical'];
            const index = Math.floor((previousDateObj.getMonth() * 31 + previousDateObj.getDate()) % 3);
            const type = types[index];
            
            if (type === 'critical') {
              prevPestWarningLevel = '高';
            } else if (type === 'outbreak') {
              prevPestWarningLevel = '中';
            }
          }
          
          // 根据预警级别计算产量
          if (prevPestWarningLevel === '高') {
            const reducedEcoScore = Math.max(60, previousEcoScore - 15);
            prevProduction = generateTeaProduction(reducedEcoScore);
          } else {
            prevProduction = generateTeaProduction(previousEcoScore);
          }
        }
        
        // 保存前一天的产量
        previousDayProduction.value = prevProduction;
        
        // 保存前一天日期
        previousDate.value = previousDateObj;
        
        // 重新获取当前日期的数据并在界面上显示
        pestHistoryRef.value.updateData(dateObj);
        
        // 更新完环境健康指数后，获取新的生态评分并更新产量
        setTimeout(() => {
          updateProductionData();
        }, 10);
      } else {
        // 如果没有计算方法，使用默认值
        previousDayProduction.value = prevProduction;
        updateProductionData();
      }
    };
    
    // 更新茶叶产量数据的函数
    const updateProductionData = () => {
      if (pestHistoryRef.value && pestHistoryRef.value.calculateAverageScore) {
        const ecoScore = pestHistoryRef.value.calculateAverageScore();
        
        // 基于生态评分更新茶叶产量
        let productionData;
        
        // 判断是否有防治措施和虫情预警级别
        if (!hasMeasures) {
          // 没有防治措施，产量上升
          const improvedEcoScore = Math.min(95, ecoScore + 8); // 提高生态评分
          productionData = calculateProductionChange(improvedEcoScore, previousDayProduction.value);
          
          // 确保是上升趋势
          productionData.trend = 'up';
          if (productionData.difference <= 0) {
            productionData.difference = Math.floor(Math.random() * 8) + 5;
            productionData.changeText = `+${productionData.difference}kg`;
            productionData.production = previousDayProduction.value + productionData.difference;
          }
        } else if (pestWarningLevel.value === '高' || pestWarningLevel.value === '中') {
          // 虫情预警级别高或中，产量下降
          // 根据级别决定下降幅度，高级别下降更多
          const reductionFactor = pestWarningLevel.value === '高' ? 15 : 8;
          const reducedEcoScore = Math.max(60, ecoScore - reductionFactor);
          productionData = calculateProductionChange(reducedEcoScore, previousDayProduction.value);
          
          // 强制设置为下降趋势
          productionData.trend = 'down';
          if (productionData.difference >= 0) {
            // 确保产量下降，高级别下降更多
            const minReduction = pestWarningLevel.value === '高' ? 8 : 3;
            const maxReduction = pestWarningLevel.value === '高' ? 15 : 8;
            const reduction = minReduction + Math.floor(Math.random() * (maxReduction - minReduction));
            
            productionData.production = Math.max(85, previousDayProduction.value - reduction);
            productionData.difference = productionData.production - previousDayProduction.value;
            productionData.changeText = `${productionData.difference}kg`;
          }
        } else {
          // 正常情况，使用计算的产量变化
          productionData = calculateProductionChange(ecoScore, previousDayProduction.value);
        }
        
        teaProduction.value = productionData.production;
        teaProductionChange.value = productionData.changeText;
        teaProductionTrend.value = productionData.trend;
      }
    };
    
    // 使用一个辅助函数来获取前一天的数据，这样不会修改UI显示
    const getYesterdayDataWithoutUI = () => {
      // 创建临时对象来存储前一天的数据
      const tempPestHistory = {
        updateData: pestHistoryRef.value.updateData,
        calculateAverageScore: pestHistoryRef.value.calculateAverageScore
      };
      
      // 使用闭包保存当前的updateData函数
      const originalUpdateData = tempPestHistory.updateData;
      
      // 执行前一天数据计算
      getAndStoreYesterdayData();
    };
    
    // 执行获取前一天数据的函数
    getYesterdayDataWithoutUI();
  }
  
  // 更新虫情防治措施
  if (pestMeasuresRef.value) {
    pestMeasuresRef.value.updateMeasures(day);
  }
  
  // 更新气象情况图表 - 确保传递正确的日期对象
  if (weatherChartRef.value && weatherChartRef.value.updateWeatherData) {
    // 检查day对象的格式，确保传递正确的日期对象
    weatherChartRef.value.updateWeatherData(dateObj);
  }
  
  // 更新饼图数据
  if (pieChartRef.value && pieChartRef.value.updateWeatherData) {
    pieChartRef.value.updateWeatherData(dateObj);
  }
}

// 页面加载时初始化饼图数据
onMounted(() => {
  // 获取今天的日期
  const today = new Date();
  
  // 检查今天是否是3月30日
  const month = today.getMonth();
  const date = today.getDate();
  if (month === 2 && date === 30) { // JavaScript中月份从0开始，2代表3月
    deviceStatus.value = '异常';
    // 显示弹窗
    setTimeout(() => {
      deviceErrorDialogVisible.value = true;
    }, 1000);
  } else {
    deviceStatus.value = '正常';
  }
  
  // 获取昨天的日期并保存
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  previousDate.value = yesterday;
  
  // 检查今天是否有防治措施
  let hasMeasures = false;
  if (pestMeasuresRef.value) {
    hasMeasures = pestMeasuresRef.value.checkHasMeasures(today);
  }
  
  // 检查昨天是否有防治措施
  let yesterdayHasMeasures = false;
  if (pestMeasuresRef.value) {
    yesterdayHasMeasures = pestMeasuresRef.value.checkHasMeasures(yesterday);
  }
  
  // 初始化虫情预警级别
  determinePestWarningLevel(today);
  
  // 先初始化昨天的环境健康指数以获取生态评分
  if (pestHistoryRef.value) {
    pestHistoryRef.value.updateData(yesterday);
    
    setTimeout(() => {
      // 获取昨天的生态评分
      if (pestHistoryRef.value && pestHistoryRef.value.calculateAverageScore) {
        const yesterdayEcoScore = pestHistoryRef.value.calculateAverageScore();
        
        // 根据昨天的生态评分和防治措施情况，计算昨天的产量
        if (!yesterdayHasMeasures) {
          const improvedEcoScore = Math.min(95, yesterdayEcoScore + 8);
          previousDayProduction.value = generateTeaProduction(improvedEcoScore);
        } else {
          // 获取昨天的虫情预警级别
          let yesterdayWarningLevel = '低'; // 默认值
          
          // 计算昨天的虫情预警级别
          const prevFixedDays = yesterday.getMonth() === 3 ? [1, 5] : [1, 3, 5];
          if (prevFixedDays.includes(yesterday.getDate())) {
            if (yesterday.getDate() === 3) {
              yesterdayWarningLevel = '中';
            }
          } else {
            // 根据规律确定类型
            const types = ['prevention', 'outbreak', 'critical'];
            const index = Math.floor((yesterday.getMonth() * 31 + yesterday.getDate()) % 3);
            const type = types[index];
            
            if (type === 'critical') {
              yesterdayWarningLevel = '高';
            } else if (type === 'outbreak') {
              yesterdayWarningLevel = '中';
            }
          }
          
          // 根据预警级别计算昨天的产量
          if (yesterdayWarningLevel === '高') {
            const reducedEcoScore = Math.max(60, yesterdayEcoScore - 15);
            previousDayProduction.value = generateTeaProduction(reducedEcoScore);
          } else {
            previousDayProduction.value = generateTeaProduction(yesterdayEcoScore);
          }
        }
        
        // 现在处理今天的数据
        pestHistoryRef.value.updateData(today);
        
        setTimeout(() => {
          if (pestHistoryRef.value && pestHistoryRef.value.calculateAverageScore) {
            const ecoScore = pestHistoryRef.value.calculateAverageScore();
            
            // 基于生态评分初始化茶叶产量
            let productionData;
            
            // 判断是否有防治措施和虫情预警级别
            if (!hasMeasures) {
              // 没有防治措施，产量上升
              const improvedEcoScore = Math.min(95, ecoScore + 8); // 提高生态评分
              productionData = calculateProductionChange(improvedEcoScore, previousDayProduction.value);
              
              // 确保是上升趋势
              productionData.trend = 'up';
              if (productionData.difference <= 0) {
                productionData.difference = Math.floor(Math.random() * 8) + 5;
                productionData.changeText = `+${productionData.difference}kg`;
                productionData.production = previousDayProduction.value + productionData.difference;
              }
            } else if (pestWarningLevel.value === '高' || pestWarningLevel.value === '中') {
              // 虫情预警级别高或中，产量下降
              // 根据级别决定下降幅度，高级别下降更多
              const reductionFactor = pestWarningLevel.value === '高' ? 15 : 8;
              const reducedEcoScore = Math.max(60, ecoScore - reductionFactor);
              productionData = calculateProductionChange(reducedEcoScore, previousDayProduction.value);
              
              // 强制设置为下降趋势
              productionData.trend = 'down';
              if (productionData.difference >= 0) {
                // 确保产量下降，高级别下降更多
                const minReduction = pestWarningLevel.value === '高' ? 8 : 3;
                const maxReduction = pestWarningLevel.value === '高' ? 15 : 8;
                const reduction = minReduction + Math.floor(Math.random() * (maxReduction - minReduction));
                
                productionData.production = Math.max(85, previousDayProduction.value - reduction);
                productionData.difference = productionData.production - previousDayProduction.value;
                productionData.changeText = `${productionData.difference}kg`;
              }
            } else {
              // 正常情况，使用计算的产量变化
              productionData = calculateProductionChange(ecoScore, previousDayProduction.value);
            }
            
            teaProduction.value = productionData.production;
            teaProductionChange.value = productionData.changeText;
            teaProductionTrend.value = productionData.trend;
          }
        }, 50);
      }
    }, 50);
  }
  
  // 使用当前日期初始化饼图
  if (pieChartRef.value && pieChartRef.value.updateWeatherData) {
    pieChartRef.value.updateWeatherData(today);
  }
  
  // 初始化天气图表
  if (weatherChartRef.value && weatherChartRef.value.updateWeatherData) {
    weatherChartRef.value.updateWeatherData(today);
  }
});

// 设备异常处理逻辑
function handleDeviceError() {
  // 处理设备异常的逻辑
  deviceStatus.value = '异常';
  deviceErrorDialogVisible.value = false;
  
  // 添加到历史记录
  addToHistory({
    title: '设备异常处理',
    content: '已处理3号灌溉控制器通信中断问题',
    time: formatDateTime(new Date()),
    type: 'device',
    typeText: '设备异常'
  });
}

// 稍后处理逻辑
function handleLaterProcess() {
  deviceErrorDialogVisible.value = false;
  
  // 添加到待办事项
  addTodoItem({
    title: '设备异常待处理',
    content: '3号灌溉控制器通信中断，请尽快处理',
    time: formatDateTime(new Date()),
    type: 'device',
    typeText: '设备异常'
  });
}

// 添加待办事项
function addTodoItem(item) {
  todoItems.value.unshift(item);
  unreadTodoCount.value++;
}

// 标记单个待办为已读
function markAsRead(index) {
  if (index >= 0 && index < todoItems.value.length) {
    // 添加到历史记录
    addToHistory(todoItems.value[index]);
    
    // 从待办中移除
    todoItems.value.splice(index, 1);
    unreadTodoCount.value = Math.max(0, unreadTodoCount.value - 1);
  }
}

// 一键已读
function markAllAsRead() {
  // 全部添加到历史记录
  todoItems.value.forEach(item => {
    addToHistory(item);
  });
  
  // 清空待办
  todoItems.value = [];
  unreadTodoCount.value = 0;
}

// 添加到历史记录
function addToHistory(item) {
  historyItems.value.unshift({...item, status: '已处理'});
}

// 显示历史记录
function showHistoryTodos() {
  historyDialogVisible.value = true;
}

// 清空历史记录
function clearHistory() {
  historyItems.value = [];
}

// 格式化日期时间
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
</script>

<style scoped>
.dashboard-container {
  padding: 12px 12px 12px 8px; /* 减小内边距 */
  min-height: 98vh;
}

.header {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 20px; /* 减小标题字号 */
  font-weight: 600;
  color: #333;
  margin: 0;
}

.todo-inbox {
  position: relative;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  margin-right: 5px;
}

.todo-inbox .icon-mail {
  font-size: 32px !important;
  width: 32px !important;
  height: 32px !important;
  color: #ffb7d8;
  filter: drop-shadow(0 2px 4px rgba(255, 183, 216, 0.3));
  -webkit-text-stroke: 1px #ffa0cb;
  transition: all 0.3s;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-5px);
  }
  100% {
    transform: translateY(0px);
  }
}

.todo-inbox:hover .icon-mail {
  color: #ffc7e0;
  filter: drop-shadow(0 3px 6px rgba(255, 183, 216, 0.5));
  -webkit-text-stroke: 1px #ffb7d8;
  transform: scale(1.15);
  animation-play-state: paused;
}

.todo-inbox:active .icon-mail {
  transform: scale(0.95);
}

.badge {
  position: absolute;
  top: -6px;
  right: -10px;
  background: linear-gradient(135deg, #ff4d4f, #f5222d);
  color: white;
  border-radius: 50%;
  width: 22px;
  height: 22px;
  font-size: 12px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: badge-pulse 1.5s infinite;
  box-shadow: 0 2px 4px rgba(245, 34, 45, 0.5);
  border: 1.5px solid white;
  z-index: 2;
}

@keyframes badge-pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 2px 4px rgba(245, 34, 45, 0.5);
  }
  50% {
    transform: scale(1.15);
    box-shadow: 0 4px 8px rgba(245, 34, 45, 0.6);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 2px 4px rgba(245, 34, 45, 0.5);
  }
}

.stat-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.custom-stat-card {
  flex: 1;
  display: flex;
  padding: 15px; /* 从20px减小到15px，减少10px总高度 */
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
  background-color: white;
}

.custom-stat-card:hover {
  transform: translateY(-5px) translateY(3px) translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  animation: cardPulse 1s infinite alternate;
}

@keyframes cardPulse {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-5px);
  }
}

.blue-card {
  border-left-color: #4096ff;
}

.blue-card .icon-box {
  background-color: rgba(64, 150, 255, 0.15);
  color: #4096ff;
}

.green-card {
  border-left-color: #52c41a;
}

.green-card .icon-box {
  background-color: rgba(82, 196, 26, 0.15);
  color: #52c41a;
}

.yellow-card {
  border-left-color: #faad14;
}

.yellow-card .icon-box {
  background-color: rgba(250, 173, 20, 0.15);
  color: #faad14;
}

.red-card {
  border-left-color: #f5222d;
}

.red-card .icon-box {
  background-color: rgba(245, 82, 45, 0.15);
  color: #f5222d;
}

.icon-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 10px;
  margin-right: 15px;
  font-size: 24px;
}

.icon-svg {
  font-size: 24px;
}

.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.value-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.value {
  font-size: 22px;
  font-weight: 600;
  color: #333;
}

.change {
  font-size: 14px;
  white-space: nowrap;
}

.change.up {
  color: #52c41a;
  position: relative;
  padding-left: 13px;
  padding-top: 5px;
}

.change.up::before {
  content: "↑";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
  font-weight: bold;
}

.change.down {
  color: #f5222d;
  position: relative;
  padding-left: 13px;
  padding-top: 5px;
}

.change.down::before {
  content: "↓";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
  font-weight: bold;
}

.charts-container {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  align-items: flex-start;
}

.chart-section {
  flex: 0.99; /* 从1.02减小到0.99，向左减少10px */
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 393px;
}

.chart-item {
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 12px 10px 20px 12px;
  height: 393px; /* 从403px减小到393px，减少10px高度 */
  overflow: hidden;
}

.chart-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px; /* 减小标题下方间距 */
  display: flex;
  align-items: center;
}

.chart-title i {
  margin-right: 8px;
  color: #409EFF;
}

.pest-calendar-section {
  flex: 1.01;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  overflow: visible;
  display: flex;
  flex-direction: column;
  height: 800px; /* 虫情防治措施高度*/
  margin-left: 0px;
}

.section-title {
  padding: 8px 12px; /* 减小标题区域的内边距 */
  border-bottom: 1px solid #eee;
  font-weight: 500;
  display: flex;
  align-items: center;
  font-size: 14px; /* 减小标题字号 */
}

.section-title i {
  margin-right: 8px;
  color: #409EFF;
}

.pest-calendar-container {
  display: flex;
  flex-direction: column;
  height: auto !important; /* 改为自动高度 */
  padding: 8px 8px 16px 8px;
  gap: 0;
  overflow: visible;
  max-height: none !important; /* 移除最大高度限制 */
}

.calendar-wrapper {
  margin-bottom: -6px; /* 减小负边距 */
  transform: scale(0.95); /* 缩小5% */
  transform-origin: top left; /* 从左上角开始缩放 */
  width: 105.26%; /* 约等于1/0.95，使内容在缩放后仍能完整显示 */
  height: auto;
  position: relative;
  z-index: 10;
}

.pest-calendar-container .calendar {
  min-height: 220px; /* 减小日历组件高度 */
  margin-bottom: 10px;
}

.pest-calendar-container .pest-history {
  min-height: 150px;
  width: 350px; /* 修改为固定宽度350px */
  flex: 0 0 350px; /* 固定宽度，不伸缩 */
  position: static; /* 移除相对定位 */
  top: auto; /* 移除向上移动 */
  z-index: auto; /* 重置z-index */
  margin: 0 left; /* 水平左对齐 */
}

.pest-calendar-container .pest-measures {
  height: 352px;    /* 今日虫情防治措施高度 */
  max-height: none !important;
  overflow-y: auto;
  width: calc(50%);
  flex: 0 0 calc(50% - 6px);
  position: absolute;
  right: 15px;
  top: -405px; /* 今日虫情防治措施高度向上移动 */
  z-index: 999 !important;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
}

.calendar-component {
  min-height: 150px;
  width: calc(100% - 100px) !important;
  max-width: calc(100% - 350px) !important;
  position: relative;
  top: -795px; /* 虫情预警日历高度向上移动*/
  left: -5px;
  z-index: 15;
  margin-left: auto;
  right: 0;
}

.pest-calendar-container :deep(.vc-container) {
  width: calc(100% - 100px) !important; /* 直接修改日历容器的宽度 */
  max-width: calc(100% - 100px) !important;
  margin-left: auto !important; /* 右对齐 */
}

.measures-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative; /* 使用相对定位 */
}

.measures-content {
  display: flex;
  gap: 10px;
  height: 100%;
  margin-top: 0;
  width: 100%;
  position: relative; /* 使用相对定位 */
  justify-content: flex-end; /* 内部元素右对齐 */
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .measures-wrapper {
    min-height: 450px;
  }
  
  .measures-content {
    height: auto;
    margin-bottom: 12px;
    gap: 10px;
    justify-content: flex-end; /* 保持右对齐 */
  }
  
  .pest-calendar-container .pest-measures {
    height: 90px; /* 小屏幕下减少高度 */
    max-height: 90px;
    width: calc(50% - 6px);
    flex: 0 0 calc(50% - 6px);
    margin-left: auto; /* 保持右对齐 */
    top: -80px; /* 向上移动 */
    overflow-y: auto; /* 确保内容可滚动 */
  }
  
  .pest-calendar-container .pest-history {
    min-height: 150px;
    width: 350px; /* 固定宽度350px */
    flex: 0 0 350px;
    margin: 0 auto; /* 水平居中 */
  }
  
  .calendar-component,
  .pest-calendar-container :deep(.vc-container) {
    width: calc(100% - 100px) !important;
    max-width: calc(100% - 100px) !important;
    margin-left: auto !important;
  }
}

@media (max-width: 768px) {
  .stat-cards {
    flex-direction: column;
  }
}

/* 移除不再需要的样式，但保留必要样式 */
.stat-cards :deep(.visitors),
.stat-cards :deep(.visitors) svg,
.stat-cards :deep(.clicks),
.stat-cards :deep(.clicks) svg {
  display: none !important;
}

.chart-title .icon-svg {
  margin-right: 6px;
  color: #409EFF;
  width: 18px !important;
  height: 18px !important;
}

.section-title .icon-svg {
  margin-right: 6px;
  color: #409EFF;
  width: 18px !important;
  height: 18px !important;
}

/* 调整图表容器的宽度 */
.charts-container {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  align-items: flex-start;
}

.chart-section {
  width: auto;
  margin: 0;
}

/* 添加虫情预警级别的样式 */
.warning-low {
  color: #52c41a !important; /* 绿色 - 低风险 */
}

.warning-medium {
  color: #faad14 !important; /* 黄色 - 中风险 */
}

.warning-high {
  color: #f5222d !important; /* 红色 - 高风险 */
}

.warning-phase {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}

.no-warning {
  color: #999 !important; /* 灰色 - 暂无预警 */
  font-size: 18px;
}

/* 设备异常弹窗样式 */
.device-error-modal {
  background-color: rgba(0, 0, 0, 0.7) !important; /* 更深的遮罩层 */
}

.device-error-dialog-container {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  margin: 0 auto !important;
}

.device-error-dialog-container :deep(.el-dialog) {
  margin: 0 auto !important;
  border: 3px solid #f5222d !important;
  border-radius: 8px !important;
  box-shadow: 0 0 20px rgba(245, 34, 45, 0.6) !important;
  background: linear-gradient(to bottom, #fff, #fff8f8) !important;
}

.device-error-dialog-container :deep(.el-dialog__header) {
  background: linear-gradient(to right, #f5222d, #ff4d4f) !important;
  color: white;
  text-align: center;
  padding: 15px 0;
  border-bottom: 2px solid #a8071a;
}

.device-error-dialog-container :deep(.el-dialog__title) {
  color: white;
  font-weight: bold;
  font-size: 22px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.device-error-dialog-container :deep(.el-dialog__body) {
  padding: 20px;
  background-color: #fff8f8;
}

.device-error-dialog {
  text-align: center;
  position: relative;
}

.device-error-dialog::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M50,0 L100,87 L0,87 Z" fill="none" stroke="rgba(245,34,45,0.1)" stroke-width="2"/></svg>') repeat;
  background-size: 100px;
  opacity: 0.1;
  pointer-events: none;
  z-index: -1;
}

.error-icon {
  font-size: 70px;
  color: #f5222d;
  margin-bottom: 10px;
  animation: blink 1s infinite alternate;
  filter: drop-shadow(0 0 5px rgba(245, 34, 45, 0.5));
}

.error-alert {
  font-size: 28px;
  font-weight: bold;
  color: #f5222d;
  margin-bottom: 15px;
  animation: blink 0.8s infinite alternate;
  text-shadow: 0 0 8px rgba(245, 34, 45, 0.5);
}

@keyframes blink {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  100% {
    opacity: 0.7;
    transform: scale(1.2);
  }
}

.error-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #cf1322;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
}

.error-content {
  margin-bottom: 20px;
  text-align: left;
  padding: 15px;
  background-color: rgba(255, 240, 240, 0.8);
  border-radius: 8px;
  border: 1px solid #ffccc7;
}

.error-solution {
  text-align: left;
  background-color: rgba(255, 240, 240, 0.8);
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #ffccc7;
}

.error-solution ol {
  margin-left: 20px;
  padding-left: 0;
}

.error-solution li {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
  margin-top: 10px;
}

.dialog-footer .el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.device-normal {
  color: #52c41a !important; /* 绿色 - 正常 */
}

.device-error {
  color: #f5222d !important; /* 红色 - 异常 */
}

/* 待办事项弹窗样式 */
.todo-dialog {
  min-height: 500px;
  max-height: 650px;
  overflow-y: auto;
}

.empty-todo, .empty-history {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
}

.empty-todo i, .empty-history i {
  font-size: 48px;
  margin-bottom: 10px;
}

.todo-item, .history-item {
  padding: 12px;
  border-radius: 6px;
  background-color: #f9f9f9;
  margin-bottom: 12px;
  border-left: 3px solid #409EFF;
}

.todo-item-header, .history-item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.todo-title, .history-title {
  font-weight: bold;
  font-size: 16px;
}

.todo-time, .history-time {
  color: #909399;
  font-size: 12px;
}

.todo-content, .history-content {
  margin-bottom: 10px;
  color: #606266;
}

.todo-footer, .history-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-type, .history-type {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.todo-type-device, .history-type-device {
  background-color: #f56c6c;
  color: white;
}

.history-status {
  color: #67c23a;
  font-size: 12px;
}

/* 历史记录弹窗样式 */
.history-dialog {
  min-height: 500px;
  max-height: 650px;
  overflow-y: auto;
}

/* 待办事项弹窗居中样式 */
.todo-dialog-container {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  margin: 0 auto !important;
}

.todo-dialog-container :deep(.el-dialog) {
  margin: 0 auto !important;
  border-radius: 8px !important;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2) !important;
}

/* 历史记录弹窗居中样式 */
.history-dialog-container {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  margin: 0 auto !important;
}

.history-dialog-container :deep(.el-dialog) {
  margin: 0 auto !important;
  border-radius: 8px !important;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2) !important;
}
</style> 